/*
 * Copyright (C) <2009> 
 *
 * <Sandeep Kumar Sinha> <sandeepksinha@gmail.com>
 * 
 * This program is free software: you can redistribute it and/or modify it 
 * under the terms of the GNU General Public License as published by the 
 * Free Software Foundation, either version 3 of the License, or (at your 
 * option) any later version->
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE->  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <libdevmapper.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <unistd.h>
#include <libgen.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/param.h>
#include <locale.h>
#include <langinfo.h>

#include <fcntl.h>
#include <sys/stat.h>
#include <stdint.h>
#include "../include/ohsm.h"
#include "ohsm_u.h"

#define MAX_DEV_NAME_LEN 20 
#define MAX_TIER_ALLOWED 11

int ohsm_get_device_topology(char *devname)
{
	int r = 0, ret = -1;
	struct dm_task *dmt;
	void *next = NULL;
	uint64_t start, length;
	char *target_type = NULL;
	char *params, *c;
	int cmd = DM_DEVICE_TABLE;
	const char *name = devname;
	struct dm_info info;
	char major[4];
	char minor[4];
	unsigned int maj,min;


	if (!(dmt = dm_task_create(cmd)))
		return -1;

	if (!dm_task_set_name(dmt, name))
		goto out;

	if (!dm_task_run(dmt))
		goto out;

	if (!dm_task_get_info(dmt, &info) || !info.exists)
		goto out;

	/* Fetch targets and print 'em */
	do {
		next = dm_get_next_target(dmt, next, &start, &length,
					  &target_type, &params);
					c = params;
					r = 0;
					while (*c && *c != ':') {
						major[r++] = *c;
						c++;
					}
					major[r] ='\0';
					c++;
					r = 0;
					while (*c && *c != ' ') {
						minor[r++] = *c;
						c++;
					}	
					minor[r] ='\0';
	
			maj = (unsigned int) atoi(major); 		
			min = (unsigned int) atoi(minor);

			dev_info->device[dev_info->dinfo_count].begin = start;
			dev_info->device[dev_info->dinfo_count].len = length;
			dev_info->device[dev_info->dinfo_count].dev_num = MKDEV(maj,min);;
			dev_info->dinfo_count++;

	ret = 0;
	} while (next);

 out:
	dm_task_destroy(dmt);
	return ret;
}

